<?php

namespace App\CustHub\Traits;

use App\CustHub\Dto\OperationLogDto;
use App\CustHub\Event\ChOperationLog;
use App\CustHub\Model\ChOpSchemeRobot;
use Hyperf\Database\Model\Builder;
use Mine\Annotation\DeleteCache;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use Mine\MineModel;
use function Hyperf\Collection\data_get;

trait OpSchemeTrait
{

    public function addGroup(array $data)
    {
        return $this->groupMapper->save($data);
    }

    public function updateGroup(mixed $id,array $data)
    {
        return $this->groupMapper->update($id,$data);
    }
    public function deleteGroup(mixed $id,mixed $type): bool
    {
        if($this->groupMapper->delete($id)){
            $this->mapper->updateByCondition(['group_id'=>$id,'type'=>$type],['group_id'=>0]);
        }
        return true;
    }

    public function groupList(array $data): array
    {
        $pageSize = data_get($data, 'page_size', MineModel::PAGE_SIZE);

        $query = $this->groupMapper->model::query()
            ->where('uid',$data['uid'])
            ->where('type',$data['type']);
        $paginate = $query
            ->orderBy('created_at','desc')
            ->paginate((int)$pageSize);

        $paginate = $this->mapper->setPaginate($paginate);
        return $paginate;
    }

    public function list(array $data): array
    {
        $pageSize = data_get($data, 'page_size', MineModel::PAGE_SIZE);

        $query = $this->mapper->model::query()
            ->where('uid',$data['uid'])
            ->where('type',$this->type);
        $paginate = $this->handleSearch($query,$data)
            ->orderBy('created_at','desc')
            ->paginate((int)$pageSize);

        $paginate = $this->mapper->setPaginate($paginate);
        if(method_exists($this,'handlePageItems')){
            $paginate['items'] = $this->handlePageItems($paginate['items'],$data);
        }
        return $paginate;
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        $name = data_get($params, 'name');

        if(!empty($name)){
            $query->where('name','like',$name.'%');
        }

        return $query;
    }

    #[Transaction]
    public function save(array $data):mixed
    {
        $data = $this->handleSaveData($data);
        $data['type'] = $this->type;
        $scheme_id = $this->mapper->save($data);
        if(method_exists($this,'afterSave')){
            $this->afterSave($scheme_id,$data);
        }

        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($data['uid'])
                ->setMainUid($data['main_uid'])
                ->setSchemeId($scheme_id)
                ->setName($data['name'])
                ->setContent('新建方案')
                ->setType($this->type)
        )));
        return $scheme_id;
    }

    public function handleSaveData(array $data): array
    {
        $cfg = data_get($data,'cfg');
        if(!empty($cfg)){
            $data['cfg'] = json_decode($data['cfg'],true);
        }
        return $data;
    }

    #[Transaction]
    public function update(mixed $id,array $data):bool
    {
        $scheme = $this->mapper->findById($id);
        if(empty($scheme)){
            throw new NormalStatusException('请选择您要编辑的方案');
        }
        $data['cfg'] = json_decode($data['cfg'],true);
        $rst = $this->mapper->update($id,$data);

        if (method_exists($this,'afterUpdate')){
            $this->afterUpdate($id,$data);
        }
        $this->mapper->deleteCache($id);

        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($data['uid'])
                ->setMainUid($data['main_uid'])
                ->setSchemeId($scheme->id)
                ->setName($scheme->name)
                ->setContent('修改方案内容')
                ->setType($scheme->type)
        )));

        return $rst;
    }

    /**
     * 重命名
     * @param mixed $id
     * @param array $data
     * @return bool
     */
    public function rename(mixed $id,array $data): bool
    {
        $this->mapper->deleteCache($id);
        $rst = $this->mapper->update($id,['name'=>$data['name']]);
        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($data['uid'])
                ->setMainUid($data['main_uid'])
                ->setSchemeId((int)$id)
                ->setName($data['name'])
                ->setContent('方案重命名')
                ->setType($this->type)
        )));
        return $rst;
    }

    /**
     * 复制
     * @param array $params
     * @return mixed
     */
    public function copy(array $params): mixed
    {
        $info = $this->mapper->findById($params['id']);
        if(empty($info)){
            return false;
        }

        $data = $info->toArray();
        $data['name'] = $data['name'].'_副本';
        unset($data['created_at'],$data['updated_at']);
        return $this->mapper->save($data);
    }

    public function deleteScheme(mixed $id): bool
    {
        $scheme = $this->mapper->model::query()->find($id);
        if (empty($scheme)) {
            throw new NormalStatusException('请选择一个方案');
        }
        ChOpSchemeRobot::query()
            ->where('scheme_id',$id)
            ->delete();
        $scheme->delete();

        if(method_exists($this,'afterDelete')){
            $this->afterDelete((int)$id);
        }
        $this->mapper->deleteCache($id);

        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($scheme->uid)
                ->setMainUid($scheme->main_uid)
                ->setSchemeId((int)$id)
                ->setName($scheme->name)
                ->setContent('删除方案')
                ->setType($scheme->type)
        )));
        return true;
    }
}